package managers;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import twitter4j.internal.org.json.JSONObject;
import managers.HashManager;


  public class EventManager {
	
    public boolean addEvent(String user_id, String element_id, String schemaName, String secretKey) throws Exception {
		
		System.setProperty("jsse.enableSNIExtension", "false");
		
			JSONObject answerJson;
			HashManager hm = new HashManager();
			String token = hm.obtainToken(schemaName, secretKey);
			String urlParameters = "ns="+schemaName+"&token="+token+"&action=PositiveFeedback&user_id="+user_id+"&element_id="+element_id;
			System.out.println(urlParameters);
			String url = "https://www.gamify.ws/api/v1/events";
 
			URL obj = new URL(url);
			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
	 		
			
			//add request header
			con.setRequestMethod("POST");
		
			con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
			con.setRequestProperty("charset", "utf-8");
			
			// Send post request
			con.setDoOutput(true);
			con.connect();
			DataOutputStream wr = new DataOutputStream(con.getOutputStream());
			wr.writeBytes(urlParameters);
			wr.flush();
			wr.close();
	 
			//int responseCode = con.getResponseCode();
			//System.out.println("\nSending 'POST' request to URL : " + url);
			//System.out.println("Post parameters : " + urlParameters);
			//System.out.println("Response Code : " + responseCode);
	 
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer responseBuffer = new StringBuffer();
	 
			while ((inputLine = in.readLine()) != null) {
				responseBuffer.append(inputLine);
			}
			in.close();
			
			String response = responseBuffer.toString();
			//print result
			System.out.println(response.toString());	
			
			answerJson = new JSONObject(response);
			
			if (answerJson.has("error"))
 				return answerJson.getBoolean("error");
			
			return false;
 	 	
}
}
